package cn.circle.mobile.controller;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.alibaba.fastjson.JSON;

import cn.circle.commom.controller.BackendBaseController;
import cn.circle.mobile.service.IUserService;
import cn.circle.system.model.CommodityInfo;
import cn.circle.system.model.OrderDeatil;
import cn.circle.system.model.OrderInfo;
import cn.circle.system.model.SysDepartment;
import cn.circle.system.model.SysNotice;
import cn.circle.system.model.SysUser;
import cn.circle.system.service.ICommodityInfoService;
import cn.circle.system.service.IOrderDeatilService;
import cn.circle.system.service.IOrderInfoService;
import cn.circle.system.service.ISysUserService;
import cn.circle.system.util.DateUtils;
import cn.circle.system.util.ReturnInfo;

@Controller
@EnableWebMvc
@SuppressWarnings({ "unchecked", "unused" })
@RequestMapping("/mobile")
public class MobileMainController extends BackendBaseController {
	private static final Log log = LogFactory.getLog(MobileMainController.class);
	
	@Autowired
	private ICommodityInfoService commodityInfoService;
	
	@Autowired
	private ISysUserService sysUserService;
	
	@Autowired
	private IOrderInfoService orderInfoService;
	
	@Autowired
	private IOrderDeatilService orderDeatilService;
	
	@Autowired
	private IUserService userService;
	
/*	 extends FrontBaseController*/
	
	/**
	 * 
	* @Title: managePage
	* @Description: TODO(前端首页)
	* @param @return    参数
	* @date 
	* @return String    返回类型
	* 
	 */
	@RequestMapping(value = "/main")
	public String managePage() {
		return "/WEB-INF/pages/mobile/main/food/mainFood.jsp";
	}
	
	@RequestMapping(value = "/foodinfo")
	public String foodinfo() {
		return "/WEB-INF/pages/mobile/main/food/food_info.jsp";
	}
	
	@RequestMapping(value = "/food")
	public String food() {
		return "/WEB-INF/pages/mobile/main/food/main.jsp";
	}
	
	/*@RequestMapping(value = "/foodmain")
	public String foodmian() {
		return "/WEB-INF/pages/mobile/main/food/commodity_main.jsp";
	}*/
	/**
	 * 
	* @Title: myorder
	* @Description: TODO(订单页面)
	* @param @return    参数
	* @date 
	* @return String    返回类型
	* @throws
	 */
	@RequestMapping(value = "/myorder")
	public String myorder() {
		return "/WEB-INF/pages/mobile/main/personalcenter/myorder.jsp";
	}
	/**
	 * 
	* @Title: goperson
	* @Description: TODO(个人中心)
	* @param @return    参数
	* @date 
	* @return 
	* @throws
	 */
	@RequestMapping(value = "/goperson")
	public String goperson() {
		return "/WEB-INF/pages/mobile/main/personalcenter/mainperson.jsp";
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/getCommodity")
	public ReturnInfo getCommodity(ReturnInfo info) {
		System.out.println("---首页---");
		List<CommodityInfo> lstAll = null;

		try {
/*			String hql = " from  CommodityInfo o where o.status = 9 and o.number > 0 order by rand()  ";*/
			String hql = " from  CommodityInfo  order by commodityId desc";
			lstAll = super.find(hql, 1, 20);
			info.setObj(lstAll);
		} catch (Exception e) {
			log.info("异常" + e.getMessage());
		}

			List<SysNotice> lstAll2 = null;

		try {
			String hql = " from  SysNotice o where o.status = 9 order by pubTime desc ";
			lstAll2 = super.find(hql, 1, 2);
			info.setRows(lstAll2.get(0));
		} catch (Exception e) {
			log.info("异常" + e.getMessage());
		}

		return info;
	}
	
	/**
	 * 进入前端商品页
	 */
	@RequestMapping(value = "/commoditySkip")
	public String commoditySkip(Integer id, Map<String, Integer> map, HttpServletRequest request) {
		map.put("id", id);
		return "/WEB-INF/pages/mobile/main/food/food_info.jsp";
	}
	
	/**
	 * 根据id获得单个商品的详细信息
	 * 
	 * @parameter id
	 * @return list
	 */
	@ResponseBody
	@RequestMapping(value = "/getComDetail")
	public ReturnInfo getComDetail(Integer id, ReturnInfo info) {

		if (id != null && !"".equals(id)) {

			List<CommodityInfo> lstAll = null;
			/*List<CustJudge> lstAll2 = null;*/

			try {
				String hql = " from  CommodityInfo o where o.status = 9 and o.commodityId = " + id + " ";
				lstAll = super.find(hql);
			/*	hql = " from  CustJudge o where o.status = 9 and o.commodityId = " + id + " order by o.id desc ";
				lstAll2 = super.find(hql);*/

				// 浏览次数加1
				hql = " update  CommodityInfo o set o.viewCount = o.viewCount + 1 where  o.commodityId = " + id;
				super.executeHql(hql);

			/*	info.setRows(lstAll2);*/
				info.setObj(lstAll);
			} catch (Exception e) {
				log.info("异常" + e.getMessage());
			}

		}
		return info;
	}
	
	
	/**
	 * 进入订单确认页 comId:商品ID
	 */
	@RequestMapping(value = "/confirmOrder")
	public String confirmOrder(HttpServletRequest request, String comId, Integer count, Map<String, Object> map) {

		if (comId != null) {
			map.put("comId", comId);
			map.put("count", count);
			List<CommodityInfo> com = commodityInfoService.getUser(comId);
			CommodityInfo info = null;
			if (com != null && com.size() == 1) {
				info = com.get(0);
				map.put("name", info.getNames());
				map.put("photo", info.getPhoto());
				map.put("price", info.getPrice());
				map.put("total_price", info.getPrice() * count);
				/*map.put("depId", info.getSysDepartment().getDepId());
				map.put("depName", info.getSysDepartment().getDepName());*/
			}
			/*if (getWUserOpenId(request) != null) {*/
			/*	List<SysUser> lst = sysUserService.getUser(request);
				SysUser c = null;
			if (lst != null && lst.size() == 1) {
				c = lst.get(0);*/
			SysUser c = new SysUser();
					map.put("userName", c.getUserName());
					map.put("address", c.getAddress());
					map.put("phone", c.getPhone());
					map.put("nickName", c.getNickName());
				/*	map.put("custId", c.getUserId());*/
				}
			/*}*/

			return"/WEB-INF/pages/mobile/main/food/confirmorder.jsp";
		/*}
		return null;*/
	}
	
	
	
	/**
	 * 成功下单页面
	 */
	@RequestMapping(value = "/successOrder")
	public String successOrder(HttpServletRequest request, Integer orderId, Map<String, Object> map) {

		map.put("orderId", orderId);

		return "/WEB-INF/pages/mobile/main/food/success_order.jsp";
	}
	/**
	 * 保存新订单
	 */
	@ResponseBody
	@RequestMapping(value = "/saveNewOrder")
	public ReturnInfo saveNewOrder(ReturnInfo info, OrderInfo o, HttpServletRequest request) {
		if (o != null) {
			try {
				/*o.setOpenId(getWUserOpenId(request));*/
				o.setSerialNumber(DateUtils.getYearMonth() + System.currentTimeMillis());
				orderInfoService.save(o);
				info.setRows(o.getOrderId());

				// 商品减去响应数量，订单数加上响应数量
				String hql = " update  CommodityInfo o set o.number = o.number - " + o.getOrderNumber()
						+ ",o.orderCount = o.orderCount + " + o.getOrderNumber() + " where  o.commodityId = "
						+ o.getCommodityInfo().getCommodityId();
				super.executeHql(hql);

			} catch (Exception e) {
				info.setMsg("保存失败");
				info.setSuccess(1);
			}

		}
		return info;
	}

	/**
	 * 进入完善资料页
	 */
	@RequestMapping(value = "/detail")
	public String detailMe(HttpServletRequest request, Map<String, Object> map) {

		return super.index("/WEB-INF/pages/mobile/main/food/userdetail.jsp", request);
		
	}
	/**
	 * 保存用户收货地址
	 */

	@ResponseBody
	@RequestMapping(value = "/saveAddress")
	public ReturnInfo saveAddress(ReturnInfo info, String address, String name, String phone, 
			HttpServletRequest request) {
		if (address != null && phone != null && name != null) {

			try {
				name = java.net.URLDecoder.decode(name, "UTF-8");
				address = java.net.URLDecoder.decode(address, "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			// 要获取session中的openID
			try {
				String hql = " SysUser s set s.userName = '" + name + "', s.phone = '" + phone
						+ "', s.address = '" + address + "',  ";
				super.executeHql(hql);
				HttpSession session = request.getSession();
			
			} catch (Exception e) {
				info.setSuccess(1);
				log.info("异常" + e.getMessage());
			}
		} else {
			info.setSuccess(1);
			info.setMsg("提交失败！");
		}
		return info;
	}
	/**
	 * 搜索商品
	 * 
	 * @parameter page 当前页 rows 每页显示记录数
	 * @return list
	 */
	@ResponseBody
	@RequestMapping(value = "/searchComm")
	public ReturnInfo searchComm(ReturnInfo info, String content, Integer page, Integer rows) {
		if (content != null && !"".equals(content)) {
			try {
				content = java.net.URLDecoder.decode(content, "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			List<CommodityInfo> lstAll = null;
			try {
				String hql = " from  CommodityInfo o where o.names like '%" + content
						+ "%'   order by createTime desc ";
				lstAll = super.find(hql, page, rows);
				info.setRows(super.count("select count(*) " + hql)); // 总记录数
				info.setObj(lstAll);
			} catch (Exception e) {
				info.setSuccess(1);
				log.info("异常" + e.getMessage());
			}
		} else {
			info.setSuccess(1);
			info.setMsg("提交失败！");
		}
		return info;
	}
	
	@ResponseBody
	@RequestMapping(value = "/mobile/getJson")
	public ReturnInfo getJson(ReturnInfo r) {
		
		String hql = "from SysDepartment ";
		
		Query query = super.sessionFactory.getCurrentSession().createQuery(hql);
		List<SysDepartment> l = query.list();
		r.setMsg("shishi");
		r.setObj(l);
		r.setSuccess(0);
		return r;
	}
	
	
	
	//菜单
	
	@RequestMapping(value = "/mainMenu")
	public String mainMenu() {
		return "/WEB-INF/pages/mobile/main/menu/mainMenu.jsp";
	}
	
	@RequestMapping(value = "/mainCart")
	public String mainCart() {
		return "/WEB-INF/pages/mobile/main/food/cart.jsp";
	}
	@RequestMapping(value = "/GotoPay")
	public String GotoPay() {
		return "/WEB-INF/pages/mobile/main/food/pay.jsp" ;
	}
	
	@RequestMapping(value = "/gomy")
	public String gomy() {
		return "/WEB-INF/pages/mobile/main/food/my.jsp";
	}
	@RequestMapping(value = "/mainAll")
	public String mainAll() {
		return "/WEB-INF/pages/mobile/main/food/commodity_main.jsp";
	}
	@ResponseBody
	@RequestMapping(value = "/getCartInfo")
	public ReturnInfo getCartInfo(String ids, ReturnInfo info) {

		if (ids != null && !"".equals(ids)) {

			List<CommodityInfo> lstAll = null;
			/*List<CustJudge> lstAll2 = null;*/

			try {
				//String hql = " from  CommodityInfo o where o.status = 9 and o.commodityId in (9,10)";
				String hql = " from  CommodityInfo o where o.status = 9 and o.commodityId in ("+ids+")";
				lstAll = super.find(hql);
			/*	hql = " from  CustJudge o where o.status = 9 and o.commodityId = " + id + " order by o.id desc ";
				lstAll2 = super.find(hql);*/

				// 浏览次数加1
				//hql = " update  CommodityInfo o set o.viewCount = o.viewCount + 1 where  o.commodityId in (:ids) ";
				//super.executeHql(hql);

			/*	info.setRows(lstAll2);*/
				info.setObj(lstAll);
			} catch (Exception e) {
				log.info("异常" + e.getMessage());
			}

		}
		return info;
	}
	
	/**
	 * 保存新订单
	 */
	@ResponseBody
	@RequestMapping(value = "/commitOrder")
	public ReturnInfo commitOrder(ReturnInfo info,OrderInfo o, String orderDeatil,String token, HttpServletRequest request) {
		
		try {	
				String phone =  userService.getUserByToken(token);
				String hql = " from  SysUser o where o.status = 9 and o.phone = "+phone+"";
				List<SysUser> sysUser = super.find(hql);
				SysUser k = sysUser.get(0);
				if(k.getAddress() == null || k.getAddress() =="" ){
					info.setSuccess(3);				
				}else{
					
					String orderNo = getFourRandom() + System.currentTimeMillis() + DateUtils.getNowDateString();
					OrderInfo orderInfo = new OrderInfo();
					orderInfo.setAddress(k.getAddress());
					orderInfo.setNickName(k.getNickName());
					orderInfo.setUserName(k.getUserName());
					orderInfo.setPhone(k.getPhone());
					orderInfo.setOrderNo(orderNo);
					orderInfo.setCreateTime(new Date());
					 List<OrderDeatil> orderDeatils = JSON.parseArray(orderDeatil, OrderDeatil.class);
					 
					 Double totalCount = (double) 0;
					 Double totalOneCount;
					 Integer orderNumber = 0;
					 for(OrderDeatil Deatil : orderDeatils){
						 
						 OrderDeatil d = new OrderDeatil(); 
						 d.setCommodityAmount(Deatil.getCommodityAmount());
						 d.setCommodityId(Deatil.getCommodityId());
						 d.setCommodityName(Deatil.getCommodityName());
						 d.setCommodityNums(Deatil.getCommodityNums());
						 d.setDtlOrderNo(orderNo);
						 d.setCreateTime(new Date());
						 orderNumber += Deatil.getCommodityNums();
						 totalOneCount = (double) (Deatil.getCommodityAmount()* Deatil.getCommodityNums());
						 totalCount += totalOneCount;
						 
						 orderDeatilService.save(d);
						 
						 String hql1 = " update  CommodityInfo o set o.number = o.number - " + Deatil.getCommodityNums()
							+ ",o.orderCount = o.orderCount + " + orderNumber + " where  o.commodityId = "
							+ Deatil.getCommodityId();
						 super.executeHql(hql1);
					 }
					 
					 orderInfo.setSerialNumber(DateUtils.getYearMonth() + System.currentTimeMillis());
					 orderInfo.setPayPrice(totalCount);
					 orderInfo.setOrderNumber(orderNumber);
					 orderInfo.setPayStatus((byte) 2);
					 orderInfo.setSendStatus((byte) 1);
					 orderInfo.setPayWay(2);
					 orderInfoService.save(orderInfo);					
				}
				//if(sysUser.equals(obj))
				info.setObj(k);		
		} catch (Exception e) {
			info.setMsg("保存失败");
			info.setSuccess(1);
		}
		return info;
	}
	
	 /**
     * 产生4位随机数(0000-9999)
     * @return 4位随机数
     */
    public static String getFourRandom(){
        Random random = new Random();
        String fourRandom = random.nextInt(10000) + "";
        int randLength = fourRandom.length();
        if(randLength<4){
          for(int i=1; i<=4-randLength; i++)
              fourRandom = "0" + fourRandom  ;
      }
        return fourRandom;
    }
	
}
